<template>
  <view>
    <TuiDrawer mode="bottom" :mask-closable="false" :visible="drawerVisible" @close="closeDrawer">
      <view class="opration-drawer">
        <view class="header">
          <text class="title">供需设置</text>
          <text
            class="ali-icon icon-guanbi1"
            style="font-size: 44rpx; color: #ccccc8; padding: 5rpx"
            @click="closeDrawer"
          ></text>
        </view>
        <view class="content">
          <UniForms :modelValue="form" ref="formRef">
            <view class="bg-white pt-12 pb-1 px-16 br-8">
              <UniFormsItem
                label="供需服务专员"
                name="sysUserId"
                required
                labelWidth="230rpx"
                labelPosition="top"
                :rules="[{ required: true, errorMessage: '请设置供需服务专员' }]"
              >
                <SetBroker
                  v-model:sys-user-id="form.sysUserId"
                  v-model:avatar="form.avatar"
                  v-model:phone="form.phone"
                  v-model:role-name="form.roleName"
                  v-model:user-name="form.sysUserName"
                ></SetBroker>
              </UniFormsItem>
            </view>

            <view class="bg-white pt-12 pb-1 px-16 br-8 mt-12">
              <UniFormsItem
                label="本供需接收合作意向是否需要秘书处审核？"
                name="applyTypeList"
                required
                labelWidth="230rpx"
                labelPosition="top"
                :rules="[{ required: true, errorMessage: '请选择意向提交方式' }]"
              >
                <UniDataCheckbox
                  v-model:modelValue="applyTypeList"
                  :localdata="[
                    { text: '无需审核', value: ApplicationTypeEnum.direct },
                    { text: '需要审核', value: ApplicationTypeEnum.match },
                  ]"
                ></UniDataCheckbox>
              </UniFormsItem>
            </view>

            <view class="bg-white pt-12 pb-1 px-16 br-8 mt-12">
              <UniFormsItem
                label="推广设置"
                name="promotionType"
                labelWidth="230rpx"
                :contentRight="true"
                :rules="[{ required: true, errorMessage: '请选择推广设置' }]"
                required
                labelPosition="top"
                :tip="{
                  showTip: true,
                  title: '跨会推广说明',
                  content: `跨会推广成功后，可与其他组织共享供需，带来更多的供需匹配成功机会。`,
                }"
              >
                <IntraInterClubPromotion
                  v-model:modelValue="form.promotionType"
                  :showType="form.showType"
                  :join-flag="!!currOp.joinFlag"
                  :disabled="
                    currOp.promotionType === PromotionTypeEnum.CrossConference &&
                    currOp.reviewStatus !== ReviewStatus.Pending
                  "
                ></IntraInterClubPromotion>
              </UniFormsItem>
            </view>

            <view class="bg-white pt-12 pb-1 px-16 br-8 mt-12">
              <UniFormsItem
                label="供需可见范围"
                name="promotionType"
                labelWidth="230rpx"
                :contentRight="true"
                :rules="[{ required: true, errorMessage: '请选择供需可见范围' }]"
              >
                <BizOppVisibilityScope
                  v-model:modelValue="form.showType"
                  :promotionType="form.promotionType"
                  :promotionFlag="form.promotionFlag"
                ></BizOppVisibilityScope>
              </UniFormsItem>
            </view>

            <view
              v-if="currOp.incentiveOpen === IncentiveOpenEnum.Yes"
              class="bg-white pt-12 pb-1 px-16 br-8 mt-12"
            >
              <Matchmake
                ref="matchmakeRef"
                :incentive-open="currOp.incentiveOpen"
                :incentive-type="currOp.incentiveType"
                :curr-promotion-commission-rate="currOp.incentiveCommissionRate"
                :curr-incentive-details="currOp.incentiveDetails"
                :estimated-scale="currOp.estimatedScale"
                :distribute-remarks="form.distributeRemarks"
                :promotion-commission-rate="form?.promotionCommissionRate"
              ></Matchmake>
            </view>
          </UniForms>

          <TButtonGroup position="fixed" :styles="{ gap: '24rpx' }" :showBackground="true">
            <TButton
              text="取消"
              type="none"
              :customStyle="{ width: '331rpx', borderRadius: '44rpx', border: '1px solid #CCCCC8' }"
              @click="closeDrawer"
            />
            <TButton
              :text="props.actionType === 'updInfo' ? '保存设置' : '同意发布'"
              type="primary"
              :customStyle="{ width: '331rpx', borderRadius: '44rpx' }"
              @click="handleAgree"
            />
          </TButtonGroup>
        </view>
      </view>
    </TuiDrawer>
  </view>
</template>
<script setup lang="ts">
  import TuiDrawer from '@/components/TuiDrawer/index.vue';
  import { computed, reactive, ref, watch, type PropType } from 'vue';
  import UniForms from '@/components/Form/uni_modules/uni-forms/uni-forms.vue';
  import UniFormsItem from '@/components/Form/uni_modules/uni-forms-item/uni-forms-item.vue';
  import SetBroker from './SetBroker.vue';
  import BizOppVisibilityScope from './BizOppVisibilityScope.vue';
  import IntraInterClubPromotion from './IntraInterClubPromotion.vue';
  import Matchmake from './Matchmake.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import type { IBusinessOpportunityList, IOpSet } from '@/api/businessOpportunities/type';
  import {
    ApplicationTypeEnum,
    IncentiveOpenEnum,
    IncentiveTypeEnum,
    PromotionTypeEnum,
    ReviewStatus,
    ShowTypeEnum,
  } from '@/enums/businessOpportunitiesEnum';
  import { boReview, getDefaultBroker, setBrokerConfig } from '@/api/businessOpportunities';
  import { Toast } from '@/utils';
  import { propTypes } from '@/utils/propTypes';
  import UniDataCheckbox from '@/components/Form/uni_modules/uni-data-checkbox/uni-data-checkbox.vue';

  const props = defineProps({
    actionType: {
      type: String as PropType<'updInfo' | 'review'>,
      default: 'updInfo',
    },
    id: propTypes.number,
  });

  const emits = defineEmits(['ok', 'drawerVisible']);

  const drawerVisible = ref(false);

  watch(
    () => drawerVisible.value,
    (val) => {
      emits('drawerVisible', val);
    },
    {
      immediate: true,
    },
  );

  const form = reactive<IOpSet>({
    boInfoId: undefined,
    applyTypeList: [],
    sysUserId: undefined,
    showType: ShowTypeEnum.AllVisible,
    promotionCommissionRate: undefined,
    distributeRemarks: '',
    promotionType: PromotionTypeEnum.CrossConference,
    avatar: '',
    sysUserName: '',
    phone: '',
    roleName: '',
  });

  // 提交方式只能选一个了，所以处理一下数组
  const applyTypeList = computed({
    get() {
      return form.applyTypeList[0];
    },
    set(val) {
      form.applyTypeList = [val];
    },
  });

  function closeDrawer() {
    drawerVisible.value = false;
  }

  const matchmakeRef = ref<InstanceType<typeof Matchmake>>();

  const formRef = ref<InstanceType<typeof UniForms>>();
  const handleAgree = async () => {
    const res = await matchmakeRef.value?.submit();
    await formRef.value.validate();
    if (res?.promotionCommissionRate !== undefined) {
      form.promotionCommissionRate = res!.promotionCommissionRate;
    }
    if (res?.distributeRemarks !== undefined) {
      form.distributeRemarks = res!.distributeRemarks;
    }

    if (props.actionType === 'updInfo') {
      await setBrokerConfig(form);
      Toast('设置成功');
      emits('ok');
    } else if (props.actionType === 'review') {
      await boReview({
        boInfoBrokerConfig: form,
        id: props.id!,
        reviewStatus: ReviewStatus.Approved,
      });
      emits('ok');
    }

    drawerVisible.value = false;
  };

  const currOp = reactive({
    incentiveOpen: undefined as IncentiveOpenEnum | undefined,
    incentiveCommissionRate: undefined as string | undefined,
    estimatedScale: undefined as string | undefined,
    incentiveType: undefined as IncentiveTypeEnum | undefined,
    incentiveDetails: undefined as string | undefined,
    joinFlag: undefined as number | undefined,
    promotionFlag: undefined as boolean | undefined,
    promotionType: undefined as PromotionTypeEnum | undefined,
    reviewStatus: undefined as ReviewStatus | undefined,
  });

  const defaultBrokerData = ref<IOpSet>();

  const open = (id: number) => {
    drawerVisible.value = true;
    getDefaultBroker(id).then((res) => {
      defaultBrokerData.value = res;
      form.applyTypeList = res.applyTypeList;
      form.boInfoId = id;
      form.promotionType = res.promotionType;
      form.showType = res.showType;
      form.sysUserId = res.sysUserId;
      form.distributeRemarks = res.distributeRemarks;
      form.promotionCommissionRate = res.promotionCommissionRate;
      form.avatar = res.avatar;
      form.phone = res.phone;
      form.sysUserName = res.sysUserName;
      form.roleName = res.roleName;
      currOp.incentiveOpen = res.incentiveOpen;
      currOp.incentiveCommissionRate = res.incentiveCommissionRate;
      currOp.estimatedScale = res.estimatedScale;
      currOp.incentiveType = res.incentiveType;
      currOp.incentiveDetails = res.incentiveDetails;
      currOp.joinFlag = res.joinFlag;
      currOp.promotionFlag = res.promotionFlag;
      currOp.promotionType = res.promotionType;
      currOp.reviewStatus = res.reviewStatus;
    });
  };

  defineExpose({
    open,
  });
</script>
<style lang="scss" scoped>
  .opration-drawer {
    .header {
      height: 96rpx;
      box-shadow: 0px -1px 0px 0px #ebedf0 inset;
      padding: 0rpx 24rpx 0rpx 32rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .title {
        font-size: 32rpx;
        line-height: 44rpx;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
    }
    .content {
      background-color: #f7f8fa;
      padding-bottom: 400rpx;
      height: 1000rpx;
      padding: 32rpx;
      overflow-y: auto;
    }
    .checklist-group {
      background-color: red;
    }
  }
</style>
